﻿using DocumentFormat.OpenXml.Lite.Core;
using DocumentFormat.OpenXml.Lite.Helper;
using DocumentFormat.OpenXml.Lite.Shared;
using DocumentFormat.OpenXml.Lite.Xml;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace DocumentFormat.OpenXml.Lite.WordprocessingML.Word.Table
{
    [XmlRoot("tblPr", Namespace = Constants.WordMain)]
    public class TableProperties : XmlSerializable
    {
        [Optional]
        [XmlElement("", Namespace = Constants.WordMain)]
        public XmlList<ITablePropElement> Properties { get; set; }

        public TableProperties()
        {
            Properties = new XmlList<ITablePropElement>();
            Properties.Changing += Properties_Changing;
        }

        #region Events

        void Properties_Changing(object sender, ListEventArgs<ITablePropElement> args)
        {
            if (args.Type == ListEventType.Remove)
                return;

            foreach (var obj in args.Objects)
            {
                if (obj.GetType().IsInheritedFrom(typeof(ITablePropElement)))
                {
                    var element = Properties.FirstOrDefault(e => e.GetType() == obj.GetType());
                    if (obj != null)
                    {
                        throw new OpenXmlException("Element with the same type (" +
                            element.GetType().ToString() + ") already added to list: " + Properties.ToString());
                    }
                }
            }
        }

        #endregion
    }
}
